package com.example.todolist.view

import android.animation.ValueAnimator
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.ProgressBar
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.todolist.R
import com.example.todolist.commen.TodoCategoryEnum
import com.example.todolist.commen.TodoStatus
import com.example.todolist.databinding.ActivityMainBinding
import com.example.todolist.receiver.NotificationReceiver
import com.example.todolist.util.LoggerTag.Companion.MAIN_NOTI
import com.example.todolist.util.NotificationUtil
import com.example.todolist.viewmodel.TodoListViewModel
import com.example.todolist.viewmodel.CategoryDetailViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch


@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    private lateinit var todoListAdapter: TodoAdapter
    private lateinit var categoryListAdapter: CategoryAdapter
    private lateinit var todoRView: RecyclerView
    private lateinit var categoryRView: RecyclerView
    private lateinit var progress: ProgressBar
    private lateinit var tvProgress: TextView
    private lateinit var radioGroup: RadioGroup
    private var selStatus: Int = TodoStatus.ALL.code

    private lateinit var binding: ActivityMainBinding
    private lateinit var broadcastReceiver: BroadcastReceiver
    private var selCategoryId = TodoCategoryEnum.CATEGORY_ALL.code;

    // 使用 by viewModels() 委托初始化 ViewModel
    private val todoViewModel: TodoListViewModel by viewModels()
    private val categoryViewModel: CategoryDetailViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        setContentView(R.layout.activity_main)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

//        categoryViewModel = ViewModelProvider(
//            this,
//            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
//        )[CategoryDetailViewModel::class.java]
        // 注册本地广播接收器
        broadcastReceiver = object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                lifecycleScope.launch {
                    if (intent.action == NotificationReceiver.ACTION_TODO_EXPIRED) {
                        val todoId = intent.getIntExtra("todoId", -1)
                        if (todoId != -1) {
                            todoViewModel.updateIsExpired(todoId, true)
                            todoViewModel.getListByStatus(selStatus, selCategoryId)
                            Log.d(MAIN_NOTI, "broadcastReceiver接收:---->---->todoid:$todoId")
                        }
                    }
                }
            }
        }

        val filter = IntentFilter(NotificationReceiver.ACTION_TODO_EXPIRED)
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, filter)
        init()
        initTodoRview()
        initCategoryRview()
        initRadioGroup()

        todoViewModel.todoList.observe(this) {
            todoListAdapter.submitList(it)
//            Log.d(LoggerTag.MAIN_TAG, "onCreate: 观察！！！")

        }
        categoryViewModel.cDetails.observe(this) {
            categoryListAdapter.submitList(it)
//            Log.d(LoggerTag.MAIN_TAG, "onCreate: 变了吗！！")
        }
        // 跳转分类添加的页面
        binding.toCategory.setOnClickListener { addCategory(it) }

        binding.addTodo.setOnClickListener { addTodo(it) }

    }

    private fun init() {
        NotificationUtil.showPermissionDialog(this)
//        val intent = Intent().apply {
//            action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
//            data = Uri.parse("package:${packageName}")
//        }
//        startActivity(intent)
        todoViewModel.initTodosExpired()
        progress = binding.progressBar
        tvProgress = binding.tvProg
        updateProgress()
        // 删除模式下的取消按钮
        binding.cancelButton.setOnClickListener {
            exitDeleteMode()
        }
        // 删除模式下的删除按钮
        binding.deleteButton.setOnClickListener {
            deleteSelectedItems()
        }
    }

    private fun initCategoryRview() {
        categoryRView = binding.category
        categoryListAdapter = CategoryAdapter(
            this,
            onSelCategory = { cateId ->
                lifecycleScope.launch {
                    // 查看分类的list
                    todoViewModel.getTodosByCateId(cateId)
                    // 记录id传入给add
                    selCategoryId = cateId
                    // 把筛选归为全部
                    radioGroup.check(R.id.all_radio)
                }
            }
        )

        categoryRView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        categoryRView.adapter = categoryListAdapter
//        Log.d(MAIN_TAG, "initCategoryRview: ")
    }

    /**
     * 更新待办列表
     */
    private fun initTodoRview() {
        todoListAdapter = TodoAdapter(
            toDetail = { todoId ->
                toTodoDetail(todoId)
            }, changeFinish = { todoId, isFinish, pos ->
                lifecycleScope.launch {
                    todoViewModel.changeFinishTodo(todoId, isFinish)
                    todoViewModel.getListByStatus(selStatus, selCategoryId)
                    updateProgress()
//                    todoListAdapter.notifyItemChanged(pos)
                }
            },
            startDelMode = {
                startDelMode()
            },
            this
        )
        todoRView = binding.todoListView
        todoRView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        todoRView.adapter = todoListAdapter
//        Log.d(MAIN_TAG, "initTodoRview: ====>success")
        val itemTouchCallback = ItemTouchHelperCallback(
            todoListAdapter, onItemMoved = { from, to ->
                lifecycleScope.launch {
                    todoViewModel.onItemMoved(from, to)
                    todoViewModel.getListByStatus(selStatus, selCategoryId)
                }
            })
        val itemTouchHelper = ItemTouchHelper(itemTouchCallback)
        itemTouchHelper.attachToRecyclerView(todoRView)
    }

    // 跳转分类页
    private fun addCategory(view: View) {
        val intent = Intent(this, CategoryActivity::class.java)
        startActivity(intent)
    }

    // 跳转添加待办
    private fun addTodo(view: View) {
        val intent = Intent(this, TodoDetailActivity::class.java)
        intent.putExtra("selCategoryId", selCategoryId)
        startActivity(intent)
    }

    // 跳转待办详情
    private fun toTodoDetail(todoId: Int) {
        val intent = Intent(this, TodoDetailActivity::class.java)
        intent.putExtra("todoId", todoId)
        startActivity(intent)
    }

    private fun updateProgress() {
        lifecycleScope.launch {
            val finCnt = todoViewModel.getFinishToDoCnt()
            val allCnt = todoViewModel.getAllToDoCnt()
            val percent = if (allCnt == 0) {
                0.0
            } else {
                Math.round(finCnt.toDouble() / allCnt * 100)
            }
            animateProgress(progress, progress.progress, percent.toInt())
            tvProgress.text = "$percent%($finCnt/$allCnt)"
        }
    }

    override fun onResume() {
        super.onResume()
        // 这里手动调用让我确信，两个页面viewModel根本不是同一个实例，
        // todo：所以可以试试把数据更新改到repository里面
        lifecycleScope.launch {
            categoryViewModel.queryCategoryDetails()
            todoViewModel.getTodosByCateId(selCategoryId)
            updateProgress()
        }
    }

    private fun animateProgress(
        progressBar: ProgressBar,
        start: Int,
        end: Int,
        duration: Long = resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
    ) {
        // 创建 ValueAnimator，从起始值到结束值
        val animator = ValueAnimator.ofInt(start, end)
        // 设置动画持续时间
        animator.duration = duration
        // 设置插值器
        animator.interpolator = AccelerateDecelerateInterpolator()
        // 监听动画更新，逐步更新进度条
        animator.addUpdateListener { valueAnimator ->
            val animatedValue = valueAnimator.animatedValue as Int
            progressBar.progress = animatedValue
        }
        // 启动动画
        animator.start()
    }

    // 开始删除模式
    private fun startDelMode() {
        binding.header.visibility = View.GONE
        binding.addTodo.visibility = View.GONE
        binding.multiSelectToolbar.visibility = View.VISIBLE
        todoViewModel.initIsSelected() // 重置选中状态
    }

    private fun exitDeleteMode() {
        lifecycleScope.launch {
            binding.header.visibility = View.VISIBLE
            binding.addTodo.visibility = View.VISIBLE
            binding.multiSelectToolbar.visibility = View.GONE
            todoViewModel.getListByStatus(selStatus, selCategoryId)
            todoListAdapter.exitAdapterDelMode()
        }
    }

    private fun deleteSelectedItems() {
        lifecycleScope.launch {
            val selectedItems = todoListAdapter.getSelectedItems()
            todoViewModel.deleteTodos(selectedItems)
            todoListAdapter.initSelectedItems()
            // 把筛选归为全部
//            radioGroup.check(R.id.all_radio)
            updateProgress()
            exitDeleteMode()
        }
    }

    private fun initRadioGroup() {
        radioGroup = binding.chooseStatus
        radioGroup.setOnCheckedChangeListener { group, checkedId ->
            lifecycleScope.launch {
                if (checkedId != -1) {
                    selStatus = when (checkedId) {
                        R.id.finished_radio -> TodoStatus.FINISHED.code
                        R.id.unfinished_radio -> TodoStatus.UPFINISHED.code
                        R.id.expired_radio -> TodoStatus.EXPIRED.code
                        else -> TodoStatus.ALL.code
                    }
                    todoViewModel.getListByStatus(selStatus, selCategoryId)
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        // 注销广播接收器，避免内存泄漏
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
    }
}
